<template>
  <div class="cart-container">
    <!-- 顶部导航 -->
    <header class="mall-header">
      <div class="container">
        <div class="header-left">
          <h1 class="mall-title">初遇小店</h1>
        </div>
        <div class="header-center">
          <div class="search-box">
            <input type="text" placeholder="搜索商品" class="search-input" v-model="searchKeyword" @input="updateSearch">
            <button class="search-button">搜索</button>
          </div>
        </div>
        <div class="header-right">
          <nav class="nav-links">
            <router-link to="/mall" class="nav-link">商城</router-link>
            <router-link to="/payment" class="nav-link">支付</router-link>
          </nav>
        </div>
      </div>
    </header>

    <!-- 购物车内容 -->
    <main class="cart-main">
      <div class="container">
        <div class="cart-header-section">
          <h2>我的购物车</h2>
          <p class="cart-count">共 {{ cartItemCount() }} 件商品</p>
        </div>

        <!-- 购物车为空 -->
        <div v-if="cartItems.length === 0" class="empty-cart-section">
          <div class="empty-cart-icon">🛒</div>
          <p>您的购物车还是空的</p>
          <router-link to="/mall" class="go-shopping-button">去购物</router-link>
        </div>

        <!-- 购物车列表 -->
        <div v-else class="cart-items-section">
          <div class="cart-items-header">
            <div class="header-checkbox">
              <input type="checkbox" id="select-all" v-model="selectAll" @change="toggleSelectAll">
              <label for="select-all">全选</label>
            </div>
            <div class="header-info">商品信息</div>
            <div class="header-price">单价</div>
            <div class="header-quantity">数量</div>
            <div class="header-subtotal">小计</div>
            <div class="header-action">操作</div>
          </div>

          <div class="cart-items-list">
            <div v-for="item in cartItems" :key="item.id" class="cart-item-row">
              <div class="item-checkbox">
                <input type="checkbox" :id="`select-item-${item.id}`" v-model="selectedItems[item.id]" @change="updateSelectAll">
                <label :for="`select-item-${item.id}`"></label>
              </div>
              <div class="item-info">
                <img :src="item.image" :alt="item.name" class="item-image">
                <div class="item-details">
                  <div class="item-name">{{ item.name }}</div>
                  <div class="item-category">{{ item.category }}</div>
                </div>
              </div>
              <div class="item-price">¥{{ item.price }}</div>
              <div class="item-quantity">
                <button class="quantity-button minus" @click="decreaseQuantity(item)" :disabled="item.quantity <= 1">-</button>
                <input type="number" class="quantity-input" v-model.number="item.quantity" @change="updateQuantity(item)">
                <button class="quantity-button plus" @click="increaseQuantity(item)">+</button>
              </div>
              <div class="item-subtotal">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
              <div class="item-action">
                <button class="remove-button" @click="removeItem(item.id)">删除</button>
              </div>
            </div>
          </div>
        </div>

        <!-- 购物车底部 -->
        <div class="cart-footer-section">
          <div class="footer-left">
            <button class="remove-selected-button" @click="removeSelectedItems" :disabled="selectedItemCount() === 0">
              删除选中商品
            </button>
          </div>
          <div class="footer-right">
            <div class="total-section">
              <div class="total-info">
                <span>已选商品 {{ selectedItemCount() }} 件</span>
                <span>合计：</span>
                <span class="total-price">¥{{ selectedTotal().toFixed(2) }}</span>
              </div>
              <button class="checkout-button" @click="goToCheckout" :disabled="selectedItemCount() === 0">
                去结算
              </button>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="mall-footer">
      <div class="container">
        <div class="footer-links">
          <div class="footer-column">
            <h4>购物指南</h4>
            <ul>
              <li><a href="#">注册与登录</a></li>
              <li><a href="#">购物流程</a></li>
              <li><a href="#">支付方式</a></li>
            </ul>
          </div>
          <div class="footer-column">
            <h4>配送服务</h4>
            <ul>
              <li><a href="#">配送范围</a></li>
              <li><a href="#">配送时间</a></li>
              <li><a href="#">配送费用</a></li>
            </ul>
          </div>
          <div class="footer-column">
            <h4>售后服务</h4>
            <ul>
              <li><a href="#">退换货政策</a></li>
              <li><a href="#">退款说明</a></li>
              <li><a href="#">投诉建议</a></li>
            </ul>
          </div>
        </div>
        <div class="footer-copyright">
          <p>&copy; 2023 初遇小店. 保留所有权利.</p>
        </div>
      </div>
    </footer>

    <!-- 提示信息 -->
    <div v-if="showToast" class="mall-toast" :class="{ show: showToast }">
      {{ toastMessage }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 购物车数据
const cartItems = ref([])

// 全选状态
const selectAll = ref(false)

// 选中的商品
const selectedItems = ref({})

// 搜索关键词
const searchKeyword = ref('')

// 提示信息
const showToast = ref(false)
const toastMessage = ref('')

// 显示提示信息
const showToastMessage = (message) => {
  toastMessage.value = message
  showToast.value = true
  
  setTimeout(() => {
    showToast.value = false
  }, 3000)
}

// 加载购物车数据
const loadCart = () => {
  const savedCart = localStorage.getItem('cart')
  if (savedCart) {
    cartItems.value = JSON.parse(savedCart)
    // 初始化选中状态
    cartItems.value.forEach(item => {
      selectedItems.value[item.id] = false
    })
  }
}

// 保存购物车数据
const saveCart = () => {
  localStorage.setItem('cart', JSON.stringify(cartItems.value))
}

// 增加商品数量
const increaseQuantity = (item) => {
  item.quantity += 1
  saveCart()
}

// 减少商品数量
const decreaseQuantity = (item) => {
  if (item.quantity > 1) {
    item.quantity -= 1
    saveCart()
  }
}

// 更新商品数量
const updateQuantity = (item) => {
  if (isNaN(item.quantity) || item.quantity < 1) {
    item.quantity = 1
  }
  saveCart()
}

// 删除商品
const removeItem = (itemId) => {
  const index = cartItems.value.findIndex(item => item.id === itemId)
  if (index > -1) {
    const removedItem = cartItems.value[index]
    cartItems.value.splice(index, 1)
    delete selectedItems.value[itemId]
    updateSelectAll()
    saveCart()
    showToastMessage(`已从购物车中移除 ${removedItem.name}`)
  }
}

// 删除选中的商品
const removeSelectedItems = () => {
  const selectedIds = Object.keys(selectedItems.value).filter(id => selectedItems.value[id])
  if (selectedIds.length > 0) {
    const removedItems = cartItems.value.filter(item => selectedIds.includes(item.id))
    cartItems.value = cartItems.value.filter(item => !selectedIds.includes(item.id))
    
    // 清除选中状态
    selectedIds.forEach(id => {
      delete selectedItems.value[id]
    })
    
    updateSelectAll()
    saveCart()
    showToastMessage(`已删除 ${removedItems.length} 件选中商品`)
  }
}

// 切换全选
const toggleSelectAll = () => {
  cartItems.value.forEach(item => {
    selectedItems.value[item.id] = selectAll.value
  })
}

// 更新全选状态
const updateSelectAll = () => {
  if (cartItems.value.length === 0) {
    selectAll.value = false
    return
  }
  
  const allSelected = cartItems.value.every(item => selectedItems.value[item.id])
  selectAll.value = allSelected
}

// 计算购物车商品总数
const cartItemCount = () => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0)
}

// 计算选中商品数量
const selectedItemCount = () => {
  return cartItems.value
    .filter(item => selectedItems.value[item.id])
    .reduce((total, item) => total + item.quantity, 0)
}

// 计算选中商品总价
const selectedTotal = () => {
  return cartItems.value
    .filter(item => selectedItems.value[item.id])
    .reduce((total, item) => total + (item.price * item.quantity), 0)
}

// 更新搜索
const updateSearch = () => {
  // 这里可以根据需要实现搜索功能
}

// 去结算
const goToCheckout = () => {
  const selectedProducts = cartItems.value.filter(item => selectedItems.value[item.id])
  if (selectedProducts.length > 0) {
    // 可以将选中的商品信息保存到本地存储，以便在支付页面使用
    localStorage.setItem('checkoutItems', JSON.stringify(selectedProducts))
    router.push('/payment')
  }
}

// 组件挂载时执行
onMounted(() => {
  // 检查用户是否已登录
  const isLoggedIn = localStorage.getItem('isLoggedIn') || sessionStorage.getItem('isLoggedIn')
  if (!isLoggedIn) {
    router.push('/login')
  }
  
  loadCart()
})
</script>

<style scoped>
.cart-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.mall-header {
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 16px 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.container {
  width: 100%;
  max-width: 1280px;
  margin: 0 auto;
  padding: 0 20px;
}

.header-left {
  float: left;
}

.mall-title {
  font-size: 24px;
  font-weight: bold;
  color: #ff6700;
  margin: 0;
}

.header-center {
  float: left;
  margin-left: 100px;
}

.search-box {
  display: flex;
  align-items: center;
}

.search-input {
  width: 400px;
  height: 40px;
  padding: 0 15px;
  border: 1px solid #e0e0e0;
  border-radius: 4px 0 0 4px;
  font-size: 14px;
  outline: none;
}

.search-button {
  height: 40px;
  padding: 0 20px;
  background-color: #ff6700;
  color: #fff;
  border: none;
  border-radius: 0 4px 4px 0;
  font-size: 14px;
  cursor: pointer;
}

.search-button:hover {
  background-color: #ff9800;
}

.header-right {
  float: right;
}

.nav-links {
  display: flex;
  align-items: center;
}

.nav-link {
  color: #333;
  text-decoration: none;
  margin-left: 30px;
  font-size: 16px;
}

.nav-link:hover {
  color: #ff6700;
}

.cart-main {
  flex: 1;
  background-color: #f5f5f5;
  padding: 40px 0;
}

.cart-header-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.cart-header-section h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.cart-count {
  margin: 10px 0 0 0;
  color: #666;
}

.empty-cart-section {
  background-color: #fff;
  padding: 60px 0;
  text-align: center;
  border-radius: 8px;
}

.empty-cart-icon {
  font-size: 80px;
  margin-bottom: 20px;
}

.empty-cart-section p {
  font-size: 16px;
  color: #666;
  margin-bottom: 30px;
}

.go-shopping-button {
  display: inline-block;
  padding: 12px 30px;
  background-color: #ff6700;
  color: #fff;
  text-decoration: none;
  border-radius: 4px;
  font-size: 16px;
}

.go-shopping-button:hover {
  background-color: #ff9800;
}

.cart-items-section {
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
}

.cart-items-header {
  display: flex;
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
  font-weight: bold;
  color: #333;
}

.header-checkbox {
  width: 60px;
  display: flex;
  align-items: center;
}

.header-info {
  flex: 1;
  padding-left: 20px;
}

.header-price {
  width: 120px;
  text-align: center;
}

.header-quantity {
  width: 150px;
  text-align: center;
}

.header-subtotal {
  width: 120px;
  text-align: center;
}

.header-action {
  width: 100px;
  text-align: center;
}

.cart-items-list {
  max-height: 500px;
  overflow-y: auto;
}

.cart-item-row {
  display: flex;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  align-items: center;
}

.cart-item-row:hover {
  background-color: #fafafa;
}

.item-checkbox {
  width: 60px;
  display: flex;
  justify-content: center;
}

.item-info {
  flex: 1;
  display: flex;
  align-items: center;
}

.item-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border: 1px solid #e0e0e0;
}

.item-details {
  margin-left: 20px;
}

.item-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-category {
  font-size: 12px;
  color: #999;
}

.item-price {
  width: 120px;
  text-align: center;
  color: #ff6700;
  font-weight: bold;
}

.item-quantity {
  width: 150px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.quantity-button {
  width: 30px;
  height: 30px;
  border: 1px solid #e0e0e0;
  background-color: #fff;
  cursor: pointer;
  font-size: 16px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.quantity-button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.quantity-input {
  width: 50px;
  height: 30px;
  text-align: center;
  border: 1px solid #e0e0e0;
  border-left: none;
  border-right: none;
}

.item-subtotal {
  width: 120px;
  text-align: center;
  font-weight: bold;
  color: #333;
}

.item-action {
  width: 100px;
  text-align: center;
}

.remove-button {
  padding: 5px 15px;
  background-color: #fff;
  color: #666;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.remove-button:hover {
  color: #ff6700;
  border-color: #ff6700;
}

.cart-footer-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.remove-selected-button {
  padding: 10px 20px;
  background-color: #fff;
  color: #666;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.remove-selected-button:hover:not(:disabled) {
  color: #ff6700;
  border-color: #ff6700;
}

.remove-selected-button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.total-section {
  display: flex;
  align-items: center;
}

.total-info {
  margin-right: 30px;
}

.total-info span {
  margin-right: 10px;
  color: #666;
}

.total-price {
  font-size: 20px;
  font-weight: bold;
  color: #ff6700;
}

.checkout-button {
  padding: 12px 40px;
  background-color: #ff6700;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
}

.checkout-button:hover:not(:disabled) {
  background-color: #ff9800;
}

.checkout-button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.mall-footer {
  background-color: #fff;
  padding: 40px 0;
  border-top: 1px solid #e0e0e0;
}

.footer-links {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30px;
}

.footer-column h4 {
  margin: 0 0 20px 0;
  font-size: 16px;
  color: #333;
}

.footer-column ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.footer-column li {
  margin-bottom: 10px;
}

.footer-column a {
  color: #666;
  text-decoration: none;
  font-size: 14px;
}

.footer-column a:hover {
  color: #ff6700;
}

.footer-copyright {
  text-align: center;
  color: #999;
  font-size: 14px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.mall-toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: #fff;
  padding: 12px 20px;
  border-radius: 4px;
  font-size: 14px;
  opacity: 0;
  transition: opacity 0.3s;
  z-index: 1000;
}

.mall-toast.show {
  opacity: 1;
}
</style>